package bandidong.dao.impl;

import bandidong.dao.AdminDAO;
import bandidong.model.Admin;
import bandidong.utils.Constant;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class AdminDAOImpl implements AdminDAO{
    
    private EntityManager em;
    
    public AdminDAOImpl(EntityManager em) {
        this.em = em;
    }
    
    @Override
    public String checkExists(Admin admin) {
        try {
            String jpaql = "SELECT a FROM Admin a WHERE a.username = :username AND a.password = :password";
            Query query = em.createQuery(jpaql);
            query.setParameter("username", admin.getUsername());
            query.setParameter("password", admin.getPassword());
            List admins = query.getResultList();
            return admins.isEmpty() ? "" : String.valueOf(((Admin)admins.get(0)).getId());
        }
        catch (Exception ex) {
            return Constant.ERROR;
        }
    }

    @Override
    public String updateAdmin(Admin admin) {
        try {
            Admin a = em.find(Admin.class, admin.getId());
            a.setUsername(admin.getUsername());
            a.setPassword(admin.getPassword());
            em.merge(a);
            return Constant.SUCCESS;
        }
        catch (Exception ex) {
            return Constant.ERROR;
        }
    }
}
